import time
import hmac
import hashlib
import base64
import urllib.parse
import requests
from API.config.read_conf import get_config


def dingding(num, case_name, api, status, msg):
    """
    通过钉钉进行报警消息推送
    :param num: 测试用例编号
    :param case_name: 测试用例名称
    :param api: 测试接口
    :param status: 响应信息
    :param msg: 报错信息
    :return: 无
    """

    # 生成签名
    timestamp = str(round(time.time() * 1000))
    secret_enc = get_config('dingding', 'secret')
    string_to_sign = f"{timestamp}\n{secret_enc}"
    hmac_code = hmac.new(secret_enc, string_to_sign.encode('utf-8'),
                         digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

    # 准备请求参数
    payload = {
        'access_token': get_config('dingding', 'access_token'),
        'timestamp': timestamp,
        'sign': sign
    }

    # 构建消息体
    body = {
        "msgtype": "text",
        "text": {
            "content": f"❗测试不通过\n轻诉-接口用例编号：{num}\n"
                       f"用例名称：{case_name}\n接口名称：{api}\n"
                       f"接口响应：{status}\n错误信息：{msg}\n跟进回复人："
        },
        "at": {
            "atMobiles": [get_config('dingding', 'at_mobiles')],
            "isAtAll": False
        }
    }

    # 发送请求
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    response = requests.post(get_config('dingding', 'webhook_url'),
                             params=payload,
                             headers=headers,
                             json=body,
                             verify=False)
    return response.json()
